package jsoupuntil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;
import java.util.*;

/**
 * Created by 13714526025 on 2018/9/17.
 */
public class HttpClientUntil {
    //带参数的Get方法(参数直接写在url后面)
    public void getWithParam(String url) throws IOException {
        HttpGet get = new HttpGet(url);
        //用来执行get方法的
        DefaultHttpClient client = new DefaultHttpClient();
        //设置连接超时
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,5000);
        //设置读取超时
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,5000);
        HttpResponse response = client.execute(get);
        String result = EntityUtils.toString(response.getEntity());

        System.out.println(result);
    }

    //带有头信息的Get请求
    public void postWithHeader(String url, String cookie) throws IOException {
        HttpGet get = new HttpGet(url);
//        //用来执行get方法的
        DefaultHttpClient client = new DefaultHttpClient();
        get.addHeader("cookie", cookie);
        HttpResponse response = client.execute(get);
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
    }

    //post请求带有头信息和Json参数的请求
    public void postWithParamAndHeader(String url) throws IOException {
        // 获取连接客户端工具
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String entityStr = null;
        HttpResponse response = null;
        // 创建POST请求对象
        HttpPost httpPost = new HttpPost(url);
        //添加json格式的参数
        JSONObject param = new JSONObject();
        param.put("name", "chengliang");
        param.put("age", "23");
        StringEntity entityParam = new StringEntity(param.toString());
        httpPost.setEntity(entityParam);

        /*
         * 添加请求头信息
         */
        // 浏览器表示
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
        // 传输的类型
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.addHeader("Cookie", "login=true");

        // 执行请求
        response = httpClient.execute(httpPost);
        // 获得响应的实体对象
        HttpEntity entity = response.getEntity();
        // 使用Apache提供的工具类进行转换成字符串
        entityStr = EntityUtils.toString(entity, "UTF-8");
        // 打印响应内容
        System.out.println(entityStr);

    }


    //post带有其他类型参数和头信息的请求
    public void postWithOtherParamAndHeader(String url) throws IOException {
        // 获取连接客户端工具
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String entityStr = null;
        HttpResponse response = null;
        // 创建POST请求对象
        HttpPost httpPost = new HttpPost(url);
        //添加除了json格式以外的任何参数
        List<NameValuePair> list = new LinkedList<NameValuePair>();
        BasicNameValuePair param1 = new BasicNameValuePair("name", "chengliang");
        BasicNameValuePair param2 = new BasicNameValuePair("age", "23");
        list.add(param1);
        list.add(param2);
        // 使用URL实体转换工具
        UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
        httpPost.setEntity(entityParam);
        /*
         * 添加请求头信息
         */
        // 浏览器表示
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
        // 传输的类型
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 执行请求
        response = httpClient.execute(httpPost);
        // 获得响应的实体对象
        HttpEntity entity = response.getEntity();
        // 使用Apache提供的工具类进行转换成字符串
        entityStr = EntityUtils.toString(entity, "UTF-8");
        // 打印响应内容
        System.out.println(entityStr);
    }

    //post发送Map集合的参数
    /*入参说明
     *
     * param url 请求地址
     * param map	请求的map数据
     * param encoding	编码格式
     *
     * */
    public static void mapPost(String url, Map<String, Object> map,String encoding) {
        DefaultHttpClient httpClient = null;
        HttpPost httpPost = null;
        String entityStr = null;
        try {
            httpClient =new DefaultHttpClient();
            httpPost = new HttpPost(url);
        //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encoding);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, encoding);
            // 打印响应内容
            System.out.println(entityStr);

            //判断响应状态码是否正确
//            int status= response.getStatusLine().getStatusCode();
//            if(status==200){
//                String result=EntityUtils.toString( response.getEntity());
//                System.out.println(result);
//            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }



    public static void mapPost1(String url, Map<String, String> map, Map<String, String> header, String encoding) {
        DefaultHttpClient httpClient = null;
        HttpPost httpPost = null;
        String entityStr = null;
        try {
            httpClient =new DefaultHttpClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encoding);
                httpPost.setEntity(entity);
            }




            List<NameValuePair> list1 = new ArrayList<NameValuePair>();
            Iterator iterator1 = header.entrySet().iterator();
            while (iterator1.hasNext()) {
                Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator1.next();
                list1.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
            }
            if (list1.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list1, encoding);
                httpPost.setEntity(entity);
            }


            HttpResponse response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, encoding);
            // 打印响应内容
            System.out.println(entityStr);

            //判断响应状态码是否正确
//            int status= response.getStatusLine().getStatusCode();
//            if(status==200){
//                String result=EntityUtils.toString( response.getEntity());
//                System.out.println(result);
//            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }


}
